<template>
  <view class="login-container">
    <view class="card-container">
      <!-- 顶部登录标题区 -->
      <view class="title-area" v-if="isLoginMode">
        <!-- <image class="logo-image" src="/static/modio平台.png" mode="aspectFit"></image> -->
        <view class="title-line"></view>
      </view>

        <!-- 顶部注册标题区 -->
      <view class="title-area" v-else>
        <text class="brand-text">
          <text class="brand-text-normal">创建新账户</text>
        </text>
        <view class="title-line"></view>
      </view>

      <!-- <view v-if="platform === 'app'"> -->
      <view v-if="platform === 'app'" >
            <!-- 登录表单 -->
      <view class="form-container" v-if="isLoginMode">
        <view class="input-item" :class="{'error': errors.username}">
          <text class="icon">👤</text>
          <input 
            type="text" 
            placeholder="用户名 / 邮箱" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.username"
            @blur="validateUsername"
          />
        </view>
        <text v-if="errors.username" class="error-text">{{ errors.username }}</text>

        <view class="input-item" :class="{'error': errors.password}">
          <text class="icon">🔒</text>
          <input 
            type="password" 
            placeholder="密码" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.password"
            @blur="validatePassword"
          />
        </view>
        <text v-if="errors.password" class="error-text">{{ errors.password }}</text>

        <view class="options-row">
          <view class="checkbox-item">
            <checkbox 
              :checked="rememberMe" 
              @change="handleRememberMeChange"
              color="#FF6B9B" 
            />
            <text class="checkbox-text">下次自动登录</text>
          </view>
          <text class="forget-password" @tap="handleForgetPassword">忘记密码</text>
        </view>

        <button class="action-button" @tap="handleLogin">登录</button>

        <view class="switch-link">
          <text class="switch-text">您还没有账户？</text>
          <text class="switch-action" @tap="toggleMode">去注册</text>
        </view>
      </view>

      <!-- 注册表单 -->
      <view class="form-container" v-else>

        <view class="input-item" :class="{'error': errors.username}">
          <text class="icon">👤</text>
          <input 
            type="text" 
            placeholder="用户名 / 邮箱" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.username"
            @blur="validateUsername"
          />
        </view>
        <text v-if="errors.username" class="error-text">{{ errors.username }}</text>

        <!-- <view class="input-item" :class="{'error': errors.phone}">
          <text class="icon">📱</text>
          <input 
            type="text" 
            placeholder="手机号" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.phone"
            @blur="validatePhone"
          />
        </view> -->
        <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>

        <view class="input-item" :class="{'error': errors.password}">
          <text class="icon">🔒</text>
          <input 
            type="password" 
            placeholder="密码（至少6位，包含字母和数字）" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.password"
            @blur="validatePassword"
          />
        </view>
        <text v-if="errors.password" class="error-text">{{ errors.password }}</text>

        <!-- <view class="input-item" :class="{'error': errors.confirmPassword}">
          <text class="icon">🔑</text>
          <input 
            type="password" 
            placeholder="确认密码" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.confirmPassword"
            @blur="validateConfirmPassword"
          />
        </view> -->
        <text v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</text>

        <view class="agreement-row">
          <checkbox 
            :checked="agreed" 
            @tap="handleAgreementChange"
            color="#FF6B9B" 
          />
          <text class="agreement-text">
            我已阅读并接受
            <text class="agreement-link" @tap="openUserAgreement">用户协议</text>
            和
            <text class="agreement-link" @tap="openPrivacyPolicy">隐私政策</text>
          </text>
        </view>

        <button class="action-button" @tap="handleRegister">注册</button>

        <view class="switch-link">
          <text class="switch-text">已经是会员？</text>
          <text class="switch-action" @tap="toggleMode">去登陆</text>
        </view>
      </view>

      </view>

      <!-- 微信登录 -->
      <view v-if="platform === 'mp-weixin'">
      
        <button class="action-button" @tap="wxlogin">微信授权登录</button>

      </view>

  

    </view>
  </view>
  
  <!-- 登录/注册加载弹窗 -->
  <view class="loading-mask" v-if="isLoading">
    <view class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">{{loadingText}}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { apiService, ApiService } from '/pages/utils/api.js'
import { useUserStore } from '/pages/store/user.js'
import StorageUtil from '/pages/utils/storage.js'

// 响应式数据
const isLoginMode = ref(true)
const form = reactive({
  username: '',
  password: '',
  phone: '',
  confirmPassword: ''
})
const errors = reactive({
  username: '',
  password: '',
  phone: '',
  confirmPassword: ''
})

// 平台
const platform = ref('')

// 记住我
const rememberMe = ref(false)

// 同意应用协议
const agreed = ref(false)

// 加载状态
const isLoading = ref(false)
const loadingText = ref('登录中...')

// 用户状态管理
const userStore = useUserStore()

const avatarUrl = ref('')
const nickname = ref('')

// const onGetPhoneNumber = async (e) => {
//   console.log(e.detail);
  
//   if (e.detail) {
//     // 获取手机号成功，执行登录逻辑
//     await wxlogin(e.detail.code)
//   } else {
//     uni.showToast({
//       title: '获取手机号失败',
//       icon: 'none'
//     })
//   }
// }

const onChooseAvatar = (e) => {
  const { avatarUrl } = e.detail 
  console.log('头像选择成功:', avatarUrl)
  avatarUrl.value = avatarUrl
}

// const wxloginCeshi = async () => {
//   const res = await apiService.getUserInfo({
//     worksheetId: "6886e6ba427a9931f8180b01",
//     rowid: '9a30eaae-ea21-4062-989b-2fa64d724a5f'
//   })
//   console.log('res', res.rows);
//   uni.setStorageSync('userInfo', res.rows[0])
//    userStore.setRowid(res.rows[0].rowid)
// }

const wxlogin = async () => {
  loadingText.value = '微信授权登录中...'

  try {
    isLoading.value = true
    
    // 获取微信登录凭证
    const loginResult = await new Promise((resolve) => {
      uni.login({
        provider: 'weixin',
        success: (res) => {
          console.log('微信登录成功:', res);
          
          if (res.code) {
            resolve({ success: true, code: res.code })
          } else {
            resolve({ success: false, message: '获取登录凭证失败' })
          }
        },
        fail: (err) => {
          console.error('微信登录失败:', err)
          resolve({ success: false, message: '微信登录失败' })
        }
      })
    })

    if (!loginResult.success) {
      uni.showToast({
        title: loginResult.message || '登录失败',
        icon: 'none'
      })
      return
    }

    // 调用后端登录接口
    const serverLoginResult = await new Promise((resolve) => {
      uni.request({
        url: 'https://www.dachen.vip/api/workflow/hooks/NjhhYzA0MWExM2JiZTE1YzY0ZDU3NzI4',
        method: 'POST',
        data: {
          code: loginResult.code,
          type: 0
          // avatarUrl: avatarUrl.value,
          // nickname: nickname.value
        },
        success: (response) => {
          if (response) {

            resolve({
              success: true,
              message: '登录成功',
              data: response.data
            })
          } else {
            resolve({
              success: false,
              message: response.data.message || '服务器登录失败'
            })
          }
        },
        fail: (error) => {
          console.error('服务器登录失败:', error)
          resolve({
            success: false,
            message: '网络错误，请检查网络连接'
          })
        }
      })
    })

    
    console.log('serverLoginResult', serverLoginResult);

    if (serverLoginResult.success) {
      
     console.log(serverLoginResult.data.data.rowid);
     const apiUserInfo = JSON.parse(serverLoginResult.data.data)
     console.log('apiUserInfo', apiUserInfo);
     
      // 将用户信息存储到本地
      uni.setStorageSync('userInfo', apiUserInfo)
      // 登录成功，保存用户信息
      userStore.setRowid(apiUserInfo.rowid)
      userStore.updateUserInfo(apiUserInfo)
      userStore.isLogin = true
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      // 延迟跳转
      setTimeout(() => {
        uni.$emit('refreshUserInfo')
        uni.switchTab({
          url: '/pages/tabs/profile/index'
        })
      }, 1500)
    } else {
      uni.showToast({
        title: serverLoginResult.message || '登录失败',
        icon: 'none'
      })
    }
    
  } catch ( error) {
    console.error('登录错误:', error)
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 页面加载时检查自动登录
onLoad(() => {
  console.log('登录页面加载')
  checkPlatform()
  checkAutoLogin()
})

// 检测平台
const checkPlatform = () => {
  try {
     const { uniPlatform } = uni.getSystemInfoSync();
    console.log('platform', uniPlatform);
    
    platform.value = uniPlatform
    
    // 根据平台执行不同逻辑
    if (uniPlatform === 'mp-weixin') {
      console.log('当前运行在微信小程序')
      // 微信小程序特定逻辑
    } else if (uniPlatform === 'app') {
      console.log('当前运行在APP端')
      // APP端特定逻辑
    } else if (uniPlatform === 'h5') {
      console.log('当前运行在H5端')
      // H5端特定逻辑
    }
  } catch (error) {
    console.error('获取系统信息失败:', error)
  }
}

// 检查自动登录
const checkAutoLogin = () => {
  try {
    // 恢复"记住我"状态
    const savedRememberMe = StorageUtil.get('rememberMe', false)
    rememberMe.value = savedRememberMe
    
    // 初始化用户状态
    userStore.initUserState()
    
    // 如果用户选择了记住我且有有效的登录状态，自动跳转
    if (savedRememberMe && userStore.hasLogin) {
      console.log('检测到有效登录状态，自动跳转')
      uni.showToast({
        title: '自动登录成功',
        icon: 'success',
        duration: 1000
      })
      
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/tabs/project/index'
        })
      }, 1000)
    } else if (savedRememberMe && !userStore.hasLogin) {
      console.log('记住我已设置但登录状态已过期，清除记住我状态')
      StorageUtil.remove('rememberMe')
      rememberMe.value = false
    } else {
      console.log('用户未选择记住我，显示登录页面')
    }
  } catch (error) {
    console.error('自动登录检查失败:', error)
  }
}

// 方法定义
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value
  clearForm()
}

const clearForm = () => {
  form.username = ''
  form.password = ''
  form.phone = ''
  form.confirmPassword = ''
  errors.username = ''
  errors.password = ''
  errors.phone = ''
  errors.confirmPassword = ''
}

const validateUsername = () => {
  if (!form.username.trim()) {
    errors.username = '请输入用户名'
    return false
  }
  errors.username = ''
  return true
}

const validatePassword = () => {
  if (!form.password.trim()) {
    errors.password = '请输入密码'
    return false
  }
  
  // 注册模式下需要验证密码强度
  if (!isLoginMode.value) {
    const password = form.password.trim()
    
    // 检查密码长度
    if (password.length < 6) {
      errors.password = '密码不能少于6位'
      return false
    }
    
    // 检查是否包含字母
    const hasLetter = /[a-zA-Z]/.test(password)
    // 检查是否包含数字
    const hasNumber = /\d/.test(password)
    
    if (!hasLetter || !hasNumber) {
      errors.password = '密码必须包含字母和数字'
      return false
    }
  }
  
  errors.password = ''
  return true
}

const validatePhone = () => {
  if (!form.phone.trim()) {
    errors.phone = '请输入手机号'
    return false
  }
  
  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(form.phone.trim())) {
    errors.phone = '请输入正确的手机号格式'
    return false
  }
  
  errors.phone = ''
  return true
}

const validateConfirmPassword = () => {
  if (!form.confirmPassword.trim()) {
    errors.confirmPassword = '请输入确认密码'
    return false
  }
  if (form.confirmPassword !== form.password) {
    errors.confirmPassword = '两次密码不一致'
    return false
  }
  errors.confirmPassword = ''
  return true
}

const handleLogin = async () => {
  if (!validateUsername() || !validatePassword()) {
    return
  }
  
  try {
    // 设置加载状态
    isLoading.value = true
    loadingText.value = '登录中...'
    
    const res = await apiService.getFilterRows({
      worksheetId: ApiService.WORKSHEETENUM.USER,
      filters: [
        {
          "controlId": "68a6b776096ba6d65c500839",
          "dataType": 2,
          "spliceType": 1,
          "filterType": 2,
          "value": form.username
        },
        {
          "controlId": "68a6b776096ba6d65c50083a",
          "dataType": 2,
          "spliceType": 1,
          "filterType": 2,
          "value": form.password
        }
      ]
    })

    console.log('登录响应:', res)
    
    const isSuccess = Array.isArray(res.rows) && res.rows.length > 0

    if (isSuccess) {
      const userRowid = res.rows[0]['rowid']
      const userInfo = res.rows[0]
      
      console.log('登录成功，用户rowid:', userRowid)
      console.log('用户信息:', userInfo)
      
      // 保存用户信息和rowid到全局状态
      userStore.login(userInfo, userRowid)
      uni.setStorageSync('userInfo', userInfo)
      userStore.setRowid(userRowid)
      
      
      // 保存"记住我"状态
      StorageUtil.set('rememberMe', rememberMe.value)
      
      // 关闭加载状态
      isLoading.value = false
      
      // 显示成功提示
      uni.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 1500
      })
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/tabs/project/index'
        })
      }, 1500)
      
    } else {
      isLoading.value = false
      uni.showToast({
        title: '用户名或密码错误',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('登录失败:', error)
    isLoading.value = false
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'none'
    })
  }
}

const handleRegister = async () => {
  
  if (!validateUsername() || !validatePassword() ) {
    return
  }
  
  // 确保agreed是布尔值，处理可能的字符串值
  const isAgreed = Boolean(agreed.value) && agreed.value !== 'false'
  
  if (!isAgreed) {
    uni.showToast({
      title: '请同意用户协议和隐私政策',
      icon: 'none'
    })
    return
  }
  
  // 设置加载状态
  isLoading.value = true
  loadingText.value = '注册中...'

  const res = await apiService.getFilterRows({
      worksheetId: ApiService.WORKSHEETENUM.USER,
      filters: [
        {
          "controlId": "68a6b776096ba6d65c500839",
          "dataType": 2,
          "spliceType": 1,
          "filterType": 2,
          "value": form.username
        }
      ]
    })

    console.log('注册响应:', res)
    
    const isSuccess = Array.isArray(res.rows) && res.rows.length > 0

    if (isSuccess) {
      isLoading.value = false
      console.log('该用户名已被注册，请重新输入用户名')
      uni.showToast({
        title: '该用户名已被注册，请重新输入用户名',
        icon: 'none'
      })
      
    } else {
      console.log('该用户名未被注册，可以注册');
      
   // 关闭加载状态
   isLoading.value = false
       await apiService.register({
        worksheetId: ApiService.WORKSHEETENUM.USER,
        controls: [
          {
            "controlId": "6886e6ba427a9931f8180b02",
            "value": form.username
          },
          {
            "controlId": "68a6b776096ba6d65c500839",
            "value": form.username
          },
          {
            "controlId": "68a6b776096ba6d65c50083a",
            "value": form.password
          },
          {
            "controlId": "6886e725427a9931f8180b17",
            "value": form.phone
          },
          {
            "controlId": "ctime",
            "value": new Date()
          }
        ]
      })

      const res = await apiService.getFilterRows({
      worksheetId: ApiService.WORKSHEETENUM.USER,
      filters: [
        {
          "controlId": "68a6b776096ba6d65c500839",
          "dataType": 2,
          "spliceType": 1,
          "filterType": 2,
          "value": form.username
        }
      ]
    })
      console.log('res', res.rows[0]);
      uni.setStorageSync('userInfo', res.rows[0])
      userStore.setRowid(res.rows[0].rowid)

      // 显示成功提示
      uni.showToast({
        title: '注册成功',
        icon: 'success',
        duration: 1500
      })
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/tabs/project/index'
        })
      }, 1500)

    
    }
}

const handleForgetPassword = () => {
  uni.showToast({
    title: '忘记密码功能开发中',
    icon: 'none'
  })
}

const openUserAgreement = () => {
  uni.showToast({
    title: '用户协议功能开发中',
    icon: 'none'
  })
}

const openPrivacyPolicy = () => {
  uni.showToast({
    title: '隐私政策功能开发中',
    icon: 'none'
  })
}

const handleAgreementChange = () => {
  console.log('agreed:', agreed.value);
  agreed.value = !agreed.value
  console.log('Updated agreed value:', agreed.value)
}

const handleRememberMeChange = () => {
  rememberMe.value = !rememberMe.value
  console.log('记住我状态:', rememberMe.value)
}
</script>

<style scoped>
  .login-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    background: linear-gradient(135deg, #E8D5FF 0%, #FFB6C1 100%);
    padding: 0 32rpx;
  }

  .card-container {
    width: 85%;
    max-width: 600rpx;
    background: #FFFFFF;
    border-radius: 24rpx;
    box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
    padding: 48rpx 32rpx;
    margin: 48rpx 0;
  }

  .title-area {
    text-align: center;
    margin-bottom: 48rpx;
  }

  .logo-image {
    width: 300rpx;
    height: 120rpx;
    margin: 0 auto 16rpx;
    display: block;
  }

  .welcome-text {
    font-size: 32rpx;
    color: #666666;
    display: block;
    margin-bottom: 16rpx;
  }

  .brand-text {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 48rpx;
    font-weight: bold;
    margin-bottom: 16rpx;
  }

  .brand-name {
    color: #000000;
  }

  .brand-o {
    color: #FF6B9B;
    position: relative;
    display: inline-block;
    width: 48rpx;
    height: 48rpx;
    background: #FF6B9B;
    border-radius: 50%;
    color: #FFFFFF;
    text-align: center;
    line-height: 48rpx;
    margin: 0 4rpx;
  }

  .brand-o::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 8rpx;
    height: 8rpx;
    background: #FFFFFF;
    border-radius: 50%;
  }

  .brand-text-normal {
    color: #666666;
    font-size: 32rpx;
    margin-left: 8rpx;
  }

  .title-line {
    width: 64rpx;
    height: 4rpx;
    background: #FF6B9B;
    margin: 8rpx auto 0;
    border-radius: 2rpx;
  }

  .register-title {
    font-size: 36rpx;
    color: #333333;
    font-weight: 500;
    margin-bottom: 32rpx;
  }

  .form-container {
    width: 100%;
  }

  .input-item {
    display: flex;
    align-items: center;
    background: #FFFFFF;
    border: 2rpx solid #E0E0E0;
    border-radius: 16rpx;
    padding: 0 24rpx;
    height: 104rpx;
    margin-bottom: 8rpx;
    transition: all 0.3s ease;
  }

  .input-item.error {
    border-color: #FF4D4F;
    border-width: 3rpx;
  }

  .icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 20rpx;
    opacity: 0.6;
  }

  input {
    flex: 1;
    font-size: 28rpx;
    color: #333333;
    height: 100%;
    border: none;
    outline: none;
  }

  .error-text {
    color: #FF4D4F;
    font-size: 24rpx;
    margin: 8rpx 0 16rpx 24rpx;
    display: block;
  }

  .options-row, .agreement-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 32rpx 0;
    font-size: 24rpx;
  }

  .checkbox-item {
    display: flex;
    align-items: center;
  }

  .checkbox-text {
    color: #666666;
    margin-left: 8rpx;
  }

  .forget-password {
    color: #1890FF;
    font-size: 24rpx;
  }

  .agreement-row {
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .agreement-text {
    color: #666666;
    font-size: 24rpx;
    margin-left: 8rpx;
    flex: 1;
  }

  .agreement-link {
    color: #1890FF;
    text-decoration: none;
  }

  .action-button {
    width: 100%;
    height: 96rpx;
    background: #FF6B9B;
    border: none;
    border-radius: 24rpx;
    color: #FFFFFF;
    font-size: 32rpx;
    font-weight: bold;
    margin: 32rpx 0;
    box-shadow: 0 4rpx 8rpx rgba(255, 107, 155, 0.3);
    transition: all 0.3s ease;
  }

  .action-button:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 4rpx rgba(255, 107, 155, 0.3);
  }

  .switch-link {
    text-align: center;
    margin-top: 32rpx;
  }

  .switch-text {
    color: #666666;
    font-size: 28rpx;
  }

  .switch-action {
    color: #FF6B9B;
    font-size: 28rpx;
    margin-left: 8rpx;
    font-weight: bold;
  }

  /* 加载弹窗样式 */
  .loading-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
  }

  .loading-container {
    background: #FFFFFF;
    border-radius: 24rpx;
    padding: 48rpx 64rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
  }

  .loading-spinner {
    width: 64rpx;
    height: 64rpx;
    border: 6rpx solid #F0F0F0;
    border-top: 6rpx solid #FF6B9B;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 24rpx;
  }

  .loading-text {
    font-size: 28rpx;
    color: #333333;
    font-weight: 500;
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }


  .user-details {
    display: flex;
    flex-direction: column;
  }

  .user-nickname {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 4rpx;
  }

  .user-desc {
    font-size: 24rpx;
    color: #999999;
  }
</style>